import os.path

import requests
from datetime import datetime
from os import makedirs


class ImageUtil:
    @classmethod
    def create_dir(cls, app_code):
        cls.dir_path = f"../static/{app_code}/images"
        makedirs(cls.dir_path) if not os.path.exists(cls.dir_path) else None

    def __init__(self, app_code=None, header={}):
        self.create_dir(app_code)
        self.header = header

    def download(self, url):
        content = requests.get(url, headers=self.header).content
        suffix = url.split('.')[-1]
        time_stamp = str(datetime.now().timestamp()).replace(".", "")
        image_name = f"{time_stamp}.{suffix}"
        with open(f"{self.dir_path}/{image_name}", "wb") as fp:
            fp.write(content)
        return image_name


if __name__ == '__main__':
    util = ImageUtil(app_code="test")
    util.download(url="https://imgo.youxihezi.net/img2021/5/23/11/2021052380140877_APP.png")
